package controller

import (
	rel "gostore/dao/relation"
	"gostore/model"
	"gostore/router"
	"gostore/util"

	"github.com/gin-gonic/gin"
)

type PermissionControllerT struct {
	BaseControllerT
}

var PermissionController = PermissionControllerT{}

// 获取角色
func (p *PermissionControllerT) GetAllByRole(c *gin.Context) {
	roleIdstr := c.Query("roles")
	if util.IsEmpty(roleIdstr) {
		p.err(c, 1, "错误的roleId")
		return
	}

	relist := []model.RelationRolePolicy{}

	err := rel.RolePolicyDao.LoadAllWithRolePolicyByRole(&relist, roleIdstr)
	if err != nil {
		p.err(c, 1, err.Error())
		return
	}

	p.ok(c, relist)
}

func (p *PermissionControllerT) GetAllTree(c *gin.Context) {
	relist := []model.RelationRolePolicy{}
	err := rel.RolePolicyDao.LoadAllWithRolePolicy(&relist)
	if err != nil {
		p.err(c, 1, err.Error())
		return
	}

	p.ok(c, relist)
}

func (p PermissionControllerT) AddNewRoutes() {
	router.AddRouteGroup("api/permission/", []router.Route{
		router.Route{
			Path:    "all",
			Method:  router.MGet,
			Handler: p.GetAllTree,
		},
		router.Route{
			Path:    "all/role",
			Method:  router.MGet,
			Handler: p.GetAllByRole,
		},
	})
}
